//
//  WLRouterViewController.m
//  WanLian
//
//  Created by muzhuang on 2018/8/30.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRouterViewController.h"
#import "WLRouterSettingVController.h"
#import "WLRouterDeviceCell.h"
#import "WLRouterDeviceController.h"
#import "UIScrollView+EmptyDataSet.h"
#import "WLRouterDeviceModel.h"
#import "WLWebViewController.h"
//#import "WLRouterRestartView.h"

@interface WLRouterViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>//,RouterSocketDelegate>
{
    UIButton *btnSetting;
    UIImageView *ivRouter;
    UILabel *labRouter;
    UILabel *labUpSpeed;
    UILabel *labUploadSpeed;
    UILabel *labDownSpeed;
    UILabel *labDownloadSpeed;
}

@property (nonatomic, strong) UITableView *tbDevices;
@property (nonatomic, strong) NSMutableArray    *arrDevices;
@property (nonatomic, strong) NSTimer *timerRefresh;

@end

@implementation WLRouterViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self connectToServer];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self closeTimerRefresh];
}

- (void)hasLoadedRouterInfo {
    [self connectToServer];
}
- (void)connectToServer {
    
    if ([[WLUseManager shareUser] isLogin])
    {
        WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
        if (socketManager.socketState==WLConnectionStateDisconnected) {
            [self routerDisconnectedUpdate];
            if ([[WLUseManager shareUser] routerModel]) {
                [self startTimer];
                [socketManager connectServerHost];
            }
        }
        else if (socketManager.socketState==WLConnectionStateConnecting)
        {
            [self startTimer];
            [self configRouterConnectingState];
        }
        else if (socketManager.socketState==WLConnectionStateRouter || socketManager.socketState==WLConnectionStateRemote)
        {
            [self updateRouterShow];
            [self startTimer];
            btnSetting.enabled = YES;
        }
    }
}
- (void)startTimer {
    
    if (_timerRefresh.valid==NO) {
        [self.timerRefresh fire];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kLoadedRouterInfo object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger guideIndex = [userDefaults integerForKey:@"maskGuideIndex"];
    if (guideIndex<3)
    {
        [self showRouterGuideMaskView];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hasLoadedRouterInfo) name:kLoadedRouterInfo object:nil];
    
    UIView *vBlueBack = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, WLScaleX(208))];
    [self.view addSubview:vBlueBack];
    [WLCommonTool addGradientColor:vBlueBack fromColor:wlblueColor toColor:wlUIColorRGB(0x2292F5)];
    
    UIImageView *ivRouterBack = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH_SCREEN_WL-76, WLScaleX(60), 76, 130)];
    ivRouterBack.image = [UIImage imageNamed:@"router_icon_back"];
    [vBlueBack addSubview:ivRouterBack];
    
    UILabel *labTitle = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-100)/2.0, WL_StatusBarHeight, 100, 44)];
    labTitle.textAlignment = NSTextAlignmentCenter;
    labTitle.font = [WLCommonTool fontTypePingFangSCMedium:17];
    labTitle.textColor = [UIColor whiteColor];
    labTitle.text = @"路由管理";
    [vBlueBack addSubview:labTitle];
    
    btnSetting = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH_SCREEN_WL-8-50, WL_StatusBarHeight, 50, 44)];
    [btnSetting setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnSetting setTitleColor:wlUnderlineColor forState:UIControlStateDisabled];
    btnSetting.titleLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
    [btnSetting setTitle:@"设置" forState:UIControlStateNormal];
    [btnSetting addTarget:self action:@selector(settingAction) forControlEvents:UIControlEventTouchUpInside];
    [vBlueBack addSubview:btnSetting];
    btnSetting.enabled = NO;
    
    ivRouter = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-60)/2.0, WLScaleX(100), 60, 58)];
    ivRouter.image = [UIImage imageNamed:@"router_disconnected"];
    [vBlueBack addSubview:ivRouter];
    
    labRouter = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-110)/2.0, CGRectGetMaxY(ivRouter.frame)+2, 110, 20)];
    labRouter.font = [WLCommonTool fontTypePingFangSCRegular:12];
    labRouter.textColor = [UIColor whiteColor];
    labRouter.alpha = 0.7;
//    labRouter.textColor = wlRGBACOLOR(0, 0, 0, 0.7);
    labRouter.textAlignment = NSTextAlignmentCenter;
    labRouter.text = @"断开连接";
    [vBlueBack addSubview:labRouter];
    
    UILabel *labDownload = [[UILabel alloc] initWithFrame:CGRectMake(labRouter.frame.origin.x-70, labRouter.frame.origin.y, 70, 20)];
    labDownload.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labDownload.textAlignment = NSTextAlignmentCenter;
    labDownload.textColor = wlUIColorRGB(0x22FFCF);
    labDownload.text = @"下载速度";
    [vBlueBack addSubview:labDownload];
    
    labDownloadSpeed = [[UILabel alloc] initWithFrame:CGRectMake(labDownload.frame.origin.x+10, labDownload.frame.origin.y-20, 50, 20)];
    labDownloadSpeed.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labDownloadSpeed.textAlignment = NSTextAlignmentCenter;
    labDownloadSpeed.textColor = wlUIColorRGB(0x25A4F5);
    labDownloadSpeed.text = @"Kb/s";
    [vBlueBack addSubview:labDownloadSpeed];
    
    labDownSpeed = [[UILabel alloc] initWithFrame:CGRectMake(labDownload.frame.origin.x-30, labDownloadSpeed.frame.origin.y-50, 130, 50)];
    labDownSpeed.font = [WLCommonTool fontTypePingFangSCRegular:36];
    labDownSpeed.textAlignment = NSTextAlignmentCenter;
    labDownSpeed.textColor = wlUIColorRGB(0x22FFCF);
    labDownSpeed.text = @"--";
    [vBlueBack addSubview:labDownSpeed];
//    labUpSpeed = [[UILabel alloc] initWithFrame:CGRectMake(labDownload.frame.origin.x-30, labDownloadSpeed.frame.origin.y-50, 130, 50)];
//    labUpSpeed.font = [WLCommonTool fontTypePingFangSCRegular:36];
//    labUpSpeed.textAlignment = NSTextAlignmentCenter;
//    labUpSpeed.textColor = wlUIColorRGB(0x22FFCF);
//    labUpSpeed.text = @"0";
//    [vBlueBack addSubview:labUpSpeed];
    
    UILabel *labUpload = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(labRouter.frame), labRouter.frame.origin.y, 70, 20)];
    labUpload.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labUpload.textAlignment = NSTextAlignmentCenter;
    labUpload.textColor = wlUIColorRGB(0xFFE62C);
    labUpload.text = @"上传速度";
    [vBlueBack addSubview:labUpload];
    
    labUploadSpeed = [[UILabel alloc] initWithFrame:CGRectMake(labUpload.frame.origin.x+10, labUpload.frame.origin.y-20, 50, 20)];
    labUploadSpeed.font = [WLCommonTool fontTypePingFangSCRegular:14];
    labUploadSpeed.textAlignment = NSTextAlignmentCenter;
    labUploadSpeed.textColor = wlUIColorRGB(0x25A4F5);
    labUploadSpeed.text = @"Kb/s";
    [vBlueBack addSubview:labUploadSpeed];
    
    labUpSpeed = [[UILabel alloc] initWithFrame:CGRectMake(labUpload.frame.origin.x-30, labUploadSpeed.frame.origin.y-50, 130, 50)];
    labUpSpeed.font = [WLCommonTool fontTypePingFangSCRegular:36];
    labUpSpeed.textAlignment = NSTextAlignmentCenter;
    labUpSpeed.textColor = wlUIColorRGB(0xFFE62C);
    labUpSpeed.text = @"--";
    [vBlueBack addSubview:labUpSpeed];
//    labDownSpeed = [[UILabel alloc] initWithFrame:CGRectMake(labUpload.frame.origin.x-30, labUploadSpeed.frame.origin.y-50, 130, 50)];
//    labDownSpeed.font = [WLCommonTool fontTypePingFangSCRegular:36];
//    labDownSpeed.textAlignment = NSTextAlignmentCenter;
//    labDownSpeed.textColor = wlUIColorRGB(0xFFE62C);
//    labDownSpeed.text = @"0";
//    [vBlueBack addSubview:labDownSpeed];
    
    _tbDevices = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbDevices.delegate = self;
    _tbDevices.dataSource = self;
    _tbDevices.rowHeight = WLScaleX(74);
    _tbDevices.tableFooterView = [UIView new];
//    if (@available(iOS 11.0, *)) {
//        _tbDevices.estimatedSectionHeaderHeight = 0;
//    }
    [self.view addSubview:_tbDevices];
    
    WLWkSelf
//    _tbDevices.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
//        [weakSelf receiveDeviceSpeed];
//        [weakSelf receiveRouterDevice];
//        [weakSelf.tbDevices.mj_header endRefreshing];
//    }];
    
    self.tbDevices.emptyDataSetSource = self;
    self.tbDevices.emptyDataSetDelegate = self;
    
    [_tbDevices mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vBlueBack.mas_bottom);
        make.left.bottom.right.equalTo(weakSelf.view);
    }];
    
    [[WLSocketManager sharedSocketManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
    
//    if ([WLSocketManager sharedSocketManager].isConnected) {
//        [self reqRouterRegister];
//    }
//    else
//    {
//        [[WLSocketManager sharedSocketManager] connectServerHost];
//        [self reqRouterRegister];
//    }
    
//    [self reqCurrentRouterInfo];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routerChangedAction) name:kNOTIFICATION_CHANGED object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routerDisconnectedUpdate) name:@"RouterDisonnected" object:nil];
}

- (void)routerDisconnectedUpdate
{
    [self closeTimerRefresh];
    [self viewUpdate];
    [self updateRouterShow];
}
- (void)closeTimerRefresh {
    if (_timerRefresh) {
        [_timerRefresh invalidate];
        _timerRefresh = nil;
    }
}
- (void)configRouterConnectingState {
    [self viewUpdate];
    [self updateRouterShow];
}

- (void)viewUpdate
{
    labUpSpeed.text = @"--";
    labUploadSpeed.text = @"Kb/s";
    labDownloadSpeed.text = @"Kb/s";
    labDownSpeed.text = @"--";
    btnSetting.enabled = NO;
    [self.arrDevices removeAllObjects];
    [self.tbDevices reloadData];
}

- (void)updateRouterShow
{
    [self updateRouterShowWithOutReloadData];
    [self.tbDevices reloadData];
}

- (void)settingAction
{
//    WLRouterRestartView *restartView = [[WLRouterRestartView alloc] init];
//    restartView.okAction = ^{
//        
//    };
//    [restartView show];
//    return;
//    [self receiveDownloadData];
////    [[WLSocketManager sharedSocketManager] disconnect];
//    return;
    WLRouterSettingVController *settingController = [[WLRouterSettingVController alloc] init];
    settingController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:settingController animated:YES];
}

- (NSTimer *)timerRefresh
{
    if (!_timerRefresh) {
        _timerRefresh = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshTimerAction) userInfo:nil repeats:YES];
    }
    return _timerRefresh;
}

- (void)routerChangedAction
{
    
}

//- (void)reqRouterRegister
//{
//    WLUserInfo *user = [[WLUseManager shareUser] getUserInformation];
//    NSDictionary *dictContent = @{@"publickey":user.userTag};
//    NSError *parseError;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictContent options:NSJSONWritingPrettyPrinted error:&parseError];
//
//    NSString *strContent = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSDictionary *dict = @{@"type":@"REGISTER",@"content":strContent};
//    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:1001];
//}

- (void)receiveRouterInfo
{
    NSDictionary *dict = @{@"type":@"DEVICE_LOADING_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}
    

- (void)receiveDeviceSpeed
{
    NSDictionary *dict = @{@"type":@"DEVICE_STATUS_UPANDDOWNSIZE_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)receiveRouterDevice
{
    NSDictionary *dict = @{@"type":@"DEVICE_NET_DEVICE_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)receiveDownloadData
{
    NSDictionary *dictContent = @{@"fileId":@"623fafwafewefafaifuaoifh",@"fileName":@"图2.png"};
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictContent options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *strContent = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *dict = @{@"type":@"DEVICE_FILE_DOWNLOAD_REQ",@"content":strContent};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}
//- (void)reqCurrentRouterInfo
//{
//    WLWkSelf
//    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/app/info" withParamsDic:nil success:^(NSDictionary *successDict) {
//
//    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
//    } error:^(NSError *error) {
//
//    } inView:self.view];
//}

- (void)refreshTimerAction
{
    WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
    if (socketManager.socketState == WLConnectionStateDisconnected)//(socketManager.routerSocket.isDisconnected||socketManager.isRegistered==NO)
    {
        [self routerDisconnectedUpdate];
    } else if (socketManager.socketState == WLConnectionStateConnecting) {
        [self configRouterConnectingState];
    }
    else if(socketManager.socketState == WLConnectionStateRouter || socketManager.socketState == WLConnectionStateRemote)
    {
        [self receiveDeviceSpeed];
        [self receiveRouterDevice];
        [self updateRouterShowWithOutReloadData];
    }
}
- (void)updateRouterShowWithOutReloadData {
    WLSocketManager *socketManager = [WLSocketManager sharedSocketManager];
    if (socketManager.socketState==WLConnectionStateRouter) {
        ivRouter.image = [UIImage imageNamed:@"router_link"];
        labRouter.text = @"近场";
        labRouter.alpha = 1.0;
    }
    else if (socketManager.socketState==WLConnectionStateRemote)
    {
        ivRouter.image = [UIImage imageNamed:@"router_remote"];
        labRouter.text = @"远场";
        labRouter.alpha = 1.0;
    }
    else
    {
        ivRouter.image = [UIImage imageNamed:@"router_disconnected"];
        labRouter.text = @"断开连接";
        labRouter.alpha = 0.7;
    }
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
    [_tbDevices.mj_header endRefreshing];
    
    if (self.timerRefresh.valid == NO) {
        
        [self.timerRefresh fire];
    }
    btnSetting.enabled = YES;
    
    if ([msgModel.type isEqualToString:@"REGISTER_SUCCESS"]) {
//        [self receiveDeviceSpeed];
////        [self receiveRouterInfo];
//        [self receiveRouterDevice];
        btnSetting.enabled = YES;
        [self updateRouterShow];
    }
    else if ([msgModel.type isEqualToString:@"DEVICE_STATUS_UPANDDOWNSIZE_RSP"]) {
        if (msgModel.content != nil) {
            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            if (dic==nil) {
                labUploadSpeed.text = @"--";
                labUpSpeed.text = @"--";
                labDownloadSpeed.text = @"--";
                labDownSpeed.text = @"--";
                return;
            }
//            labUpSpeed.text = [NSString stringWithFormat:@"%@",dic[@"up"]];
//            labDownSpeed.text = [NSString stringWithFormat:@"%@",dic[@"down"]];
            float upSpeed = [dic[@"up"] integerValue]/1024.0;
            NSString *strUp = [NSString stringWithFormat:@"%.f",upSpeed];
            if (upSpeed>1024)
            {
                strUp = [NSString stringWithFormat:@"%.f",upSpeed/1024.0];
                labUploadSpeed.text = @"Mb/s";
            }
            else
            {
                labUploadSpeed.text = @"Kb/s";
            }
            labUpSpeed.text = strUp;
            
            float downSpeed = [dic[@"down"] integerValue]/1024.0;
            NSString *strDown = [NSString stringWithFormat:@"%.f",downSpeed];
            if (downSpeed>1024) {
                strDown = [NSString stringWithFormat:@"%.f",downSpeed/1024.0];
                labDownloadSpeed.text = @"Mb/s";
            }
            else
            {
                labDownloadSpeed.text = @"Kb/s";
            }
            labDownSpeed.text = strDown;
        }
    }
    else if ([msgModel.type isEqualToString:@"DEVICE_NET_DEVICE_REP"])
    {
        self.arrDevices = [WLRouterDeviceModel mj_objectArrayWithKeyValuesArray:msgModel.content];
        [self.tbDevices reloadData];
    }
    else if ([msgModel.type isEqualToString:@"COMMON_ERROR"])
    {
//        [self routerDisconnectedUpdate];
//        [self viewUpdate];
//        [self updateRouterShow];
    }
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strDevice = @"deviceCell";
    WLRouterDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:strDevice];
    if (!cell) {
        cell = [[WLRouterDeviceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strDevice];
    }
    WLRouterDeviceModel *model = self.arrDevices[indexPath.row];
    cell.routerDevices = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WLRouterDeviceModel *model = self.arrDevices[indexPath.row];
    WLRouterDeviceController *deviceController = [[WLRouterDeviceController alloc] init];
    deviceController.deviceModel = model;
    deviceController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:deviceController animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
/*
#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    if ([WLSocketManager sharedSocketManager].routerSocket.isDisconnected||[WLSocketManager sharedSocketManager].isRegistered==NO) {
        return [UIImage imageNamed:@"disconnect"];
    }
    return [UIImage imageNamed:@"no_data"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"";
    if ([WLSocketManager sharedSocketManager].routerSocket.isDisconnected||[WLSocketManager sharedSocketManager].isRegistered==NO) {
        title = @"路由器已经断开连接";
    }
    else
    {
        title = @"还没有设备连接~";
    }
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    if ([WLSocketManager sharedSocketManager].routerSocket.isDisconnected||[WLSocketManager sharedSocketManager].isRegistered==NO) {
        NSAttributedString *strTitle = [[NSAttributedString alloc] initWithString:@"连接帮助" attributes:@{NSFontAttributeName:[WLCommonTool fontTypePingFangSCMedium:14],NSForegroundColorAttributeName:wlblueColor}];
        return strTitle;
    }
    else
    {
        return nil;
    }
}

- (UIImage *)buttonBackgroundImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    if ([WLSocketManager sharedSocketManager].routerSocket.isDisconnected||[WLSocketManager sharedSocketManager].isRegistered==NO) {
        UIEdgeInsets capInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
        UIEdgeInsets rectInsets = UIEdgeInsetsMake(0.0, -(WIDTH_SCREEN_WL-80-40)/2.0, 0.0, -(WIDTH_SCREEN_WL-80-40)/2.0);
        UIImage *imgBack = [[[UIImage imageNamed:@"btn_rectangle"] resizableImageWithCapInsets:capInsets resizingMode:UIImageResizingModeStretch] imageWithAlignmentRectInsets:rectInsets];
        return imgBack;
    }
    else
    {
        return nil;
    }
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    WLWebViewController *webView = [[WLWebViewController alloc] init];
    webView.urlStr = @"http://47.75.195.106/help/usehelp.html";
//    webView.titleStr = @"";
    webView.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
}
*/
- (void)routerLinkHelp
{
    WLSocketManager *manager = [WLSocketManager sharedSocketManager];
    if (manager.socketState==WLConnectionStateDisconnected) {
        if ([[WLUseManager shareUser] routerModel]) {
            [self startTimer];
            [self configRouterConnectingState];
            [manager connectServerHost];
        } else {
            [[WLUseManager shareUser] requestRouterInfo];
        }
    } else {
        
        WLWebViewController *webView = [[WLWebViewController alloc] init];
//        webView.urlStr = @"http://47.75.195.106/help/usehelp.html";
        webView.urlStr = [NSString stringWithFormat:@"%@/help/usehelp.html",[WLCommonTool getWebHost]];
        //    webView.titleStr = @"";
        webView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webView animated:YES];
    }
}

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
{
    UIView *noMsgView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, _tbDevices.bounds.size.height)];
    
    UIImageView *ivNoTip;// = [[UIImageView alloc] initWithImage:imgTip];
//    UIImage *imgTip;
    NSString *strTitle;
    WLSocketManager *manager = [WLSocketManager sharedSocketManager];
    if (manager.socketState==WLConnectionStateDisconnected)//([WLSocketManager sharedSocketManager].routerSocket.isDisconnected||[WLSocketManager sharedSocketManager].isRegistered==NO)
    {
        UIImage *imgTip = [UIImage imageNamed:@"disconnect"];
        ivNoTip = [[UIImageView alloc] initWithImage:imgTip];
        strTitle = @"路由器已经断开连接";
        
        UIButton *btnLink = [[UIButton alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-120)/2.0, noMsgView.center.y+imgTip.size.height/2.0+WLScaleX(30), 120, 30)];
        [btnLink setTitleColor:wlblueColor forState:UIControlStateNormal];
        btnLink.titleLabel.font = [WLCommonTool fontTypePingFangSCMedium:14];
//        [btnLink setTitle:@"连接帮助" forState:UIControlStateNormal];
        [btnLink setTitle:@"重新连接" forState:UIControlStateNormal];
        [btnLink addTarget:self action:@selector(routerLinkHelp) forControlEvents:UIControlEventTouchUpInside];
        [noMsgView addSubview:btnLink];
        btnLink.layer.cornerRadius = 5;
        btnLink.layer.masksToBounds = YES;
        btnLink.layer.borderWidth = 1.0;
        btnLink.layer.borderColor = wlblueColor.CGColor;
    }
    else if (manager.socketState==WLConnectionStateConnecting)//||manager.socketState==WLConnectionStateConnected)
    {
        UIImage *imgTip = [UIImage imageNamed:@"router_connecting_1"];
        ivNoTip = [[UIImageView alloc] initWithImage:imgTip];
        ivNoTip.animationImages = @[[UIImage imageNamed:@"router_connecting_1"],[UIImage imageNamed:@"router_connecting_2"],[UIImage imageNamed:@"router_connecting_3"],[UIImage imageNamed:@"router_connecting_4"],[UIImage imageNamed:@"router_connecting_5"],[UIImage imageNamed:@"router_connecting_6"],[UIImage imageNamed:@"router_connecting_7"]];
        ivNoTip.animationDuration = 1.4;
        [ivNoTip startAnimating];
        strTitle = @"正在连接路由器…";
        
        UIButton *btnLink = [[UIButton alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-120)/2.0, noMsgView.center.y+imgTip.size.height/2.0+WLScaleX(10), 120, 30)];
        [btnLink setTitleColor:wlblueColor forState:UIControlStateNormal];
        btnLink.titleLabel.font = [WLCommonTool fontTypePingFangSCMedium:14];
        [btnLink setTitle:@"连接帮助" forState:UIControlStateNormal];
        [btnLink addTarget:self action:@selector(routerLinkHelp) forControlEvents:UIControlEventTouchUpInside];
        [noMsgView addSubview:btnLink];
        btnLink.layer.cornerRadius = 5;
        btnLink.layer.masksToBounds = YES;
        btnLink.layer.borderWidth = 1.0;
        btnLink.layer.borderColor = wlblueColor.CGColor;
    }
    else
    {
        UIImage *imgTip = [UIImage imageNamed:@"no_data"];
        ivNoTip = [[UIImageView alloc] initWithImage:imgTip];
        strTitle = @"还没有设备连接~";
    }
    
    ivNoTip.center = CGPointMake(noMsgView.center.x, noMsgView.center.y-WLScaleX(50));
    [noMsgView addSubview:ivNoTip];
    
    UILabel *labTip = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMaxY(ivNoTip.frame)+WLScaleX(20), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(30))];
    labTip.textAlignment = NSTextAlignmentCenter;
    labTip.font = [WLCommonTool fontTypePingFangSCRegular:17];
    labTip.textColor = wlDarkGrayColor;
    labTip.text = strTitle;
    [noMsgView addSubview:labTip];
    
    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:noMsgView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:_tbDevices.bounds.size.height];
    [noMsgView addConstraint:heightConstraint];
    
    return noMsgView;
}

//- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
//{
//    return YES;
//}
#pragma mark - 设置新手引导蒙层
- (void)showRouterGuideMaskView
{
    WLWkSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (weakSelf.isViewLoaded&&weakSelf.view.window)
        {
            CGRect frame = [UIScreen mainScreen].bounds;
            UIView *bgView = [[UIView alloc]initWithFrame:frame];
            bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
            [weakSelf.tabBarController.view addSubview:bgView];
            if (weakSelf.arrDevices.count>0)
            {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                if (weakSelf.arrDevices.count>1) {
                    indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                }
                CGRect rectCell = [weakSelf.tbDevices rectForRowAtIndexPath:indexPath];
                CGRect cutRect = [weakSelf.tbDevices convertRect:rectCell toView:bgView];
                
                UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
                [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];
                
                CAShapeLayer *shapeLayer = [CAShapeLayer layer];
                shapeLayer.path = path.CGPath;
                [bgView.layer setMask:shapeLayer];
                
                UIImageView *ivArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mask_arrow_ltop"]];
                ivArrow.center = CGPointMake(WLScaleX(90)+22, CGRectGetMaxY(cutRect)+WLScaleX(10)+17);
                [bgView addSubview:ivArrow];
                
                UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"router_first_text"]];
                ivText.center = CGPointMake(WLScaleX(95)+43+89, CGRectGetMaxY(cutRect)+WLScaleX(10)+35);
                [bgView addSubview:ivText];
                
                UIButton *btnNext = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(18), 90, 30)];
                [btnNext setBackgroundImage:[UIImage imageNamed:@"mask_next_btn"] forState:UIControlStateNormal];
                [btnNext addTarget:self action:@selector(routerFirstMaskAction:) forControlEvents:UIControlEventTouchUpInside];
                [bgView addSubview:btnNext];
            }
            else
            {
                CGRect cutRect = [weakSelf.view convertRect:CGRectMake(WIDTH_SCREEN_WL-66, WL_StatusBarHeight, 66, 44) toView:bgView];
                
                UIBezierPath *path = [UIBezierPath bezierPathWithRect:bgView.frame];
                [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];
                
                CAShapeLayer *shapeLayer = [CAShapeLayer layer];
                shapeLayer.path = path.CGPath;
                [bgView.layer setMask:shapeLayer];
                
                UIImageView *ivArrow = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMidX(cutRect)-43, CGRectGetMaxY(cutRect)+5, 43, 35)];
                ivArrow.image = [UIImage imageNamed:@"router_second_arrow"];
                [bgView addSubview:ivArrow];
                
                UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"router_second_text"]];
                ivText.center = CGPointMake(CGRectGetMinX(ivArrow.frame)-WLScaleX(10)-98, CGRectGetMaxY(ivArrow.frame));
                [bgView addSubview:ivText];
                
                UIButton *btnSecond = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(15), 90, 30)];
                [btnSecond setBackgroundImage:[UIImage imageNamed:@"mask_know_btn"] forState:UIControlStateNormal];
                [btnSecond addTarget:weakSelf action:@selector(routerMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
                [bgView addSubview:btnSecond];
            }
        }
        WLLog(@"3333333-------%lu",(unsigned long)self.arrDevices.count)
    });
}

- (void)routerFirstMaskAction:(UIButton *)btnNext
{
    UIView *bgView = btnNext.superview;
    
    NSArray *arrLayers = [NSArray arrayWithArray:bgView.layer.sublayers];
    for (CALayer *subLayer in arrLayers) {
        if ([subLayer isKindOfClass:[CAGradientLayer class]])
        {
            [subLayer removeFromSuperlayer];
        }
    }
    
    for (UIView *subView in bgView.subviews)
    {
        [subView removeFromSuperview];
    }
    
    CGRect cutRect = [self.view convertRect:CGRectMake(WIDTH_SCREEN_WL-66, WL_StatusBarHeight, 66, 44) toView:bgView];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:bgView.frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    UIImageView *ivArrow = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMidX(cutRect)-43, CGRectGetMaxY(cutRect)+5, 43, 35)];
    ivArrow.image = [UIImage imageNamed:@"router_second_arrow"];
    [bgView addSubview:ivArrow];
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"router_second_text"]];
    ivText.center = CGPointMake(CGRectGetMinX(ivArrow.frame)-WLScaleX(10)-98, CGRectGetMaxY(ivArrow.frame));
    [bgView addSubview:ivText];
    
    UIButton *btnSecond = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(15), 90, 30)];
    [btnSecond setBackgroundImage:[UIImage imageNamed:@"mask_know_btn"] forState:UIControlStateNormal];
    [btnSecond addTarget:self action:@selector(routerMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnSecond];
}

- (void)routerMaskViewAction:(UIButton *)btnOver
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:3 forKey:@"maskGuideIndex"];
    UIView *view = btnOver.superview;
    [view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
